package com.jeecms.cms.api.admin.main;

import com.jeecms.cms.api.ApiResponse;
import com.jeecms.cms.api.ApiValidate;
import com.jeecms.cms.api.Constants;
import com.jeecms.cms.api.ResponseCode;
import com.jeecms.cms.entity.assist.Branch;
import com.jeecms.cms.entity.assist.CmsEnterprise;
import com.jeecms.cms.manager.main.BranchMng;
import com.jeecms.cms.manager.main.CmsEnterpriseMng;
import com.jeecms.common.page.Pagination;
import com.jeecms.common.util.StrUtils;
import com.jeecms.common.web.ResponseUtils;
import com.jeecms.core.manager.CmsLogMng;
import com.jeecms.core.web.WebErrors;
import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 前台会员注册Action
 * Created by hashan on 2018-02-03.
 */
@Controller
public class EnterpriseApiAct {
    private static final Logger log = LoggerFactory.getLogger(EnterpriseApiAct.class);

    @RequestMapping(value = "/enterprise/list", method = RequestMethod.POST)
    public void enterpriseList(Integer pageNo,Integer pageSize,HttpServletRequest request, HttpServletResponse response) {
        String body="\"\"";
        String message= Constants.API_MESSAGE_SUCCESS;
        String code = ResponseCode.API_CODE_CALL_SUCCESS;
        if (pageNo==null) {
            pageNo=1;
        }
        if (pageSize==null) {
            pageSize=10;
        }
        Map<String, Object> params = new HashMap<>();
        params.put("pageNo", pageNo);
        params.put("pageSize", pageSize);
        if(StringUtils.isNotBlank(request.getParameter("name"))){
            params.put("name",  request.getParameter("name"));
        }
        if(StringUtils.isNotBlank(request.getParameter("contacts"))){
            params.put("contacts", request.getParameter("contacts"));
        }
        if(StringUtils.isNotBlank(request.getParameter("branchId"))){
            params.put("branchId", Integer.parseInt(request.getParameter("branchId")));
        }
        if(StringUtils.isNotBlank(request.getParameter("invitationCode"))){
            params.put("invitationCode", request.getParameter("invitationCode"));
        }
        if(StringUtils.isNotBlank(request.getParameter("industry"))){
            params.put("industry", request.getParameter("industry"));
        }
        if(StringUtils.isNotBlank(request.getParameter("legalPerson"))) {
            params.put("legalPerson", request.getParameter("legalPerson"));
        }
        Pagination page = cmsEnterpriseMng.getPage(params);
        int totalCount = page.getTotalCount();
        List<CmsEnterprise> list = (List<CmsEnterprise>) page.getList();
        JSONArray jsonArray=new JSONArray();
        if(list!=null&&list.size()>0){
            for(int i=0;i<list.size();i++){
                jsonArray.put(i, list.get(i).convertToJson());
            }
        }
        body=jsonArray.toString() +",\"totalCount\":"+totalCount;
        log.info("body:\t" + body);
        ApiResponse apiResponse=new ApiResponse(request, body, message,code);
        ResponseUtils.renderApiJson(response, request, apiResponse);
    }

    /**
     * 企业详情
     * @param id 主键
     * @param request '
     * @param response '
     */
    @RequestMapping("/enterprise/get")
    public void get(Integer id,HttpServletRequest request,HttpServletResponse response){
        String body = "\"\"";
        String message = Constants.API_MESSAGE_PARAM_REQUIRED;
        String code = ResponseCode.API_CODE_PARAM_REQUIRED;
        CmsEnterprise bean;
        if (id!=null) {
            if (id.equals(0)) {
                bean =  new CmsEnterprise();
            }else{
                bean = cmsEnterpriseMng.findById(id);
            }
            if (bean!=null) {
                body = bean.convertToJson().toString();
                message = Constants.API_MESSAGE_SUCCESS;
                code = ResponseCode.API_CODE_CALL_SUCCESS;
            }else{
                message = Constants.API_MESSAGE_OBJECT_NOT_FOUND;
                code = ResponseCode.API_CODE_NOT_FOUND;
            }
        }
        ApiResponse apiResponse = new ApiResponse(request, body, message, code);
        ResponseUtils.renderApiJson(response, request, apiResponse);
    }

    @RequestMapping(value = "/enterprise/save")
    public void save(CmsEnterprise bean, String branchIds, HttpServletRequest request, HttpServletResponse response){
        String body="\"\"";
        String message, code;
        WebErrors errors = WebErrors.create(request);
        //判断当前企业邀请码是否存在
        errors = validateInvitationCode(errors, bean, null, branchIds, request, response);
        if(!errors.hasErrors()){
            Set<Branch> set = new HashSet<Branch>();
            String[] branchs = branchIds.split(",");
            if(branchs.length >0){
                for(int i=0; i<branchs.length; i++) {
                    Branch branch = new Branch(Integer.parseInt(branchs[i]));
                    set.add(branch);
                }
            }
            bean.setBranchs(set);
            bean = cmsEnterpriseMng.save(bean);
            log.info("save Enterprise id={}, name={}", bean.getId(), bean.getName());
            cmsLogMng.operating(request, "enterprise.log.save", "id=" + bean.getId() + ";title=" + bean.getName());
            body="{\"id\":"+"\""+bean.getId()+"\"}";
            message=Constants.API_MESSAGE_SUCCESS;
            code = ResponseCode.API_CODE_CALL_SUCCESS;
        }else{
            message=errors.getErrors().get(0);
            code = ResponseCode.API_CODE_PARAM_ERROR;
        }
        ApiResponse apiResponse=new ApiResponse(request, body, message,code);
        ResponseUtils.renderApiJson(response, request, apiResponse);
    }

    @RequestMapping(value = "/enterprise/update")
    public void update(CmsEnterprise bean, String branchIds, String newInviteCode, HttpServletRequest request, HttpServletResponse response){
        String body="\"\"";
        String message, code;
        //验证公共非空参数
        WebErrors errors = WebErrors.create(request);
        //判断当前企业邀请码是否存在
        errors = validateInvitationCode(errors, bean, newInviteCode, branchIds, request, response);
        if(!errors.hasErrors()){
            Set<Branch> set = new HashSet<Branch>();
            String[] branchs = branchIds.split(",");
            if(branchs.length >0){
                for(int i=0; i<branchs.length; i++) {
                    Branch branch = new Branch(Integer.parseInt(branchs[i]));
                    set.add(branch);
                }
            }
            bean.setBranchs(set);
            bean.setInvitationCode(newInviteCode);
            bean = cmsEnterpriseMng.update(bean);
            log.info("update enterprise id={}.", bean.getId());
            cmsLogMng.operating(request, "enterprise.log.update", "id=" + bean.getId() + ";name=" + bean.getName());
            body="{\"id\":"+"\""+bean.getId()+"\"}";
            message=Constants.API_MESSAGE_SUCCESS;
            code = ResponseCode.API_CODE_CALL_SUCCESS;
        }else{
            message=errors.getErrors().get(0);
            code = ResponseCode.API_CODE_PARAM_ERROR;
        }
        ApiResponse apiResponse=new ApiResponse(request, body, message,code);
        ResponseUtils.renderApiJson(response, request, apiResponse);
    }

    @RequestMapping("/enterprise/delete")
    public void delete(String ids, HttpServletRequest request, HttpServletResponse response) {
        Integer[]idArray=null;
        String body="\"\"";
        String message, code;
        WebErrors errors=WebErrors.create(request);
        //验证公共非空参数
        errors=ApiValidate.validateRequiredParams(request,errors,ids);
        if(StringUtils.isNotBlank(ids)){
            idArray= StrUtils.getInts(ids);
        }
        if(idArray==null||idArray.length<=0){
            errors.addErrorString(Constants.API_MESSAGE_APP_PARAM_ERROR);
            message=Constants.API_MESSAGE_PARAM_REQUIRED;
            code = ResponseCode.API_CODE_PARAM_ERROR;
        }else{
            message=Constants.API_MESSAGE_DELETE_ERROR;
            code = ResponseCode.API_CODE_DELETE_ERROR;
        }
        if(!errors.hasErrors()){
            try {
                CmsEnterprise[] beans = cmsEnterpriseMng.deleteByIds(idArray);
                message=Constants.API_MESSAGE_SUCCESS;
                code = ResponseCode.API_CODE_CALL_SUCCESS;
                for (CmsEnterprise bean : beans) {
                    log.info("delete Enterprise id={}", bean.getId());
                    cmsLogMng.operating(request, "enterprise.log.delete", "id=" + bean.getId() + ";title=" + bean.getName());
                }
            } catch (Exception e) {
                message = Constants.API_MESSAGE_DELETE_ERROR;
                code = ResponseCode.API_CODE_DELETE_ERROR;
            }
        }
        ApiResponse apiResponse=new ApiResponse(request, body, message,code);
        ResponseUtils.renderApiJson(response, request, apiResponse);
    }

    private WebErrors validateInvitationCode(WebErrors errors, CmsEnterprise bean, String newInviteCode, String branchIds, HttpServletRequest request, HttpServletResponse response){
        //验证公共非空参数
        errors= ApiValidate.validateRequiredParams(request,errors,  bean.getName(), bean.getInvitationCode(), branchIds);
        if(!errors.hasErrors()) {
            if(StringUtils.isBlank(newInviteCode)){ //新增企业
                CmsEnterprise enterprise = cmsEnterpriseMng.getEnterpriseByInvitationCode(bean.getInvitationCode());
                if(enterprise != null && enterprise.getId() != null){
                    errors.addErrorString("企业邀请码已存在");
                }
            }else if(!bean.getInvitationCode().equals(newInviteCode)){//修改企业
                CmsEnterprise updateEn = cmsEnterpriseMng.getEnterpriseByInvitationCode(newInviteCode);
                if(updateEn != null && updateEn.getId() != null){
                    errors.addErrorString("企业邀请码已存在");
                }
            }
        }
        return errors;
    }

    @Autowired
    private CmsLogMng cmsLogMng;
    @Autowired
    private CmsEnterpriseMng cmsEnterpriseMng;
    @Autowired
    private BranchMng branchMng;
}
